package org.petstore.web.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.petstore.domain.Product;
import org.petstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class CompleteSearchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得搜索框中输入的关键字
        String inputKeyword=req.getParameter("keyword");

        //获得搜索的产品列表
        CatalogService catalogService=new CatalogService();
        List<Product> productList=catalogService.searchProductList(inputKeyword);

        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();

        JSONArray searchArray=new JSONArray();
        for(int i=0;i<productList.size();i++){
            //产品名字
            JSONObject searchObject=new JSONObject();
            searchObject.put("name",productList.get(i).getName());
            //添加到数组中
            searchArray.add(searchObject);
        }
        //转换成JSON字符串
        String str=searchArray.toJSONString();

        out.print(str);
    }
}
